<template>
  <div v-if="show" class="auth-modal">
    <div class="modal-overlay" @click="handleClose"></div>
    <div class="modal-content">
      <div class="modal-header">
        <h2>{{ isLogin ? '登录' : '注册' }}</h2>
        <button class="close-btn" @click="handleClose">×</button>
      </div>

      <div class="modal-body">
        <div v-if="error" class="error-message">
          {{ error }}
        </div>

        <form @submit.prevent="handleSubmit">
          <div v-if="!isLogin" class="form-group">
            <label>用户名</label>
            <input
              v-model="form.username"
              type="text"
              placeholder="请输入用户名"
              required
              :disabled="isLoading"
            />
          </div>

          <div v-if="!isLogin" class="form-group">
            <label>邮箱</label>
            <input
              v-model="form.email"
              type="email"
              placeholder="请输入邮箱"
              required
              :disabled="isLoading"
            />
          </div>

          <div v-if="isLogin" class="form-group">
            <label>用户名或邮箱</label>
            <input
              v-model="form.usernameOrEmail"
              type="text"
              placeholder="请输入用户名或邮箱"
              required
              :disabled="isLoading"
            />
          </div>

          <div class="form-group">
            <label>密码</label>
            <input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              required
              :disabled="isLoading"
            />
            <small v-if="!isLogin" class="form-hint">
              密码必须包含大小写字母和数字，至少8位
            </small>
          </div>

          <div v-if="!isLogin" class="form-group">
            <label>确认密码</label>
            <input
              v-model="form.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              required
              :disabled="isLoading"
            />
            <small v-if="form.confirmPassword && form.password !== form.confirmPassword" class="error-hint">
              两次输入的密码不一致
            </small>
          </div>

          <div v-if="!isLogin" class="form-group">
            <label>昵称</label>
            <input
              v-model="form.nickname"
              type="text"
              placeholder="请输入昵称"
              required
              :disabled="isLoading"
            />
          </div>

          <button type="submit" class="btn btn-primary" :disabled="isLoading || !isFormValid">
            {{ isLoading ? '处理中...' : (isLogin ? '登录' : '注册') }}
          </button>
        </form>

        <div class="modal-footer">
          <p>
            {{ isLogin ? '还没有账号？' : '已有账号？' }}
            <a href="#" @click.prevent="toggleMode">
              {{ isLogin ? '立即注册' : '立即登录' }}
            </a>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { useAuthStore } from '@/stores/auth';

interface Props {
  show: boolean;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  close: [];
}>();

const authStore = useAuthStore();

const isLogin = ref(true);
const isLoading = computed(() => authStore.isLoading);
const authError = computed(() => authStore.error);
const localError = ref<string | null>(null);
const error = computed(() => localError.value || authError.value);

// 检查表单是否有效
const isFormValid = computed(() => {
  if (isLogin.value) {
    return form.value.usernameOrEmail && form.value.password;
  } else {
    return (
      form.value.username &&
      form.value.email &&
      form.value.password &&
      form.value.confirmPassword &&
      form.value.nickname &&
      form.value.password === form.value.confirmPassword
    );
  }
});

const form = ref({
  username: '',
  email: '',
  usernameOrEmail: '',
  password: '',
  confirmPassword: '',
  nickname: '',
});

function resetForm() {
  form.value = {
    username: '',
    email: '',
    usernameOrEmail: '',
    password: '',
    confirmPassword: '',
    nickname: '',
  };
  authStore.clearError();
  localError.value = null;
}

function toggleMode() {
  isLogin.value = !isLogin.value;
  resetForm();
}

async function handleSubmit() {
  try {
    localError.value = null;
    if (isLogin.value) {
      await authStore.login(form.value.usernameOrEmail, form.value.password);
    } else {
      // 验证确认密码
      if (form.value.password !== form.value.confirmPassword) {
        localError.value = '两次输入的密码不一致';
        return;
      }
      await authStore.register({
        username: form.value.username,
        email: form.value.email,
        password: form.value.password,
        nickname: form.value.nickname,
      });
    }
    handleClose();
  } catch (e) {
    // 错误已在store中处理
  }
}

function handleClose() {
  resetForm();
  emit('close');
}

// 监听show变化，重置表单
watch(
  () => props.show,
  (newShow) => {
    if (newShow) {
      resetForm();
    }
  }
);
</script>

<style lang="scss" scoped>
.auth-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: relative;
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
  animation: slideUp 0.3s ease;
}

@keyframes slideUp {
  from {
    transform: translateY(20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;

  h2 {
    margin: 0;
    font-size: 1.5rem;
  }

  .close-btn {
    background: none;
    border: none;
    font-size: 2rem;
    cursor: pointer;
    color: #999;
    padding: 0;
    width: 30px;
    height: 30px;

    &:hover {
      color: #333;
    }
  }
}

.modal-body {
  padding: 20px;
}

.error-message {
  background: #fee;
  color: #c33;
  padding: 10px;
  border-radius: 6px;
  margin-bottom: 15px;
  font-size: 0.9rem;
}

.form-group {
  margin-bottom: 15px;

  label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
    color: #333;
  }

  input {
    width: 100%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 1rem;

    &:focus {
      outline: none;
      border-color: #4A90E2;
    }

    &:disabled {
      background: #f5f5f5;
      cursor: not-allowed;
    }
  }

  .form-hint {
    display: block;
    margin-top: 5px;
    color: #666;
    font-size: 0.85rem;
  }

  .error-hint {
    display: block;
    margin-top: 5px;
    color: #c33;
    font-size: 0.85rem;
  }
}

.btn {
  width: 100%;
  padding: 12px;
  margin-top: 10px;

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

.modal-footer {
  margin-top: 20px;
  text-align: center;
  color: #666;

  a {
    color: #4A90E2;
    text-decoration: none;
    font-weight: bold;

    &:hover {
      text-decoration: underline;
    }
  }
}
</style>
